package com.jsyl.lwbk.web.controller.system;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.jsyl.lwbk.business.domain.education.CheckCodeResponse;
import com.jsyl.lwbk.business.handle.RestFullService;
import com.jsyl.lwbk.common.config.Global;
import com.jsyl.lwbk.common.constant.Constants;
import com.jsyl.lwbk.framework.util.ShiroUtils;
import com.jsyl.lwbk.system.domain.CenterResponse;
import com.jsyl.lwbk.system.domain.SysMenu;
import com.jsyl.lwbk.system.domain.SysUser;
import com.jsyl.lwbk.system.service.ISysConfigService;
import com.jsyl.lwbk.system.service.ISysMenuService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jsyl.lwbk.common.core.controller.BaseController;
import com.jsyl.lwbk.common.core.domain.AjaxResult;
import com.jsyl.lwbk.common.utils.ServletUtils;
import com.jsyl.lwbk.common.utils.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录验证
 *
 *
 */
@Controller
public class SysLoginController extends BaseController {
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RestFullService restFullService;

    @Value("${spring.profiles.active}")
    private String ACTIVE;

    @Value("${jms.sso.url}")
    private String jmsSsoUrl;

    private String luosimaoapiKey = "d2b791d823da60e97798ab55aca35c81";


    @GetMapping("/checkAdmin")
    @ResponseBody
    public String checkAdmin(@RequestParam String userName) {
        Map queryMap = Maps.newHashMap();
        queryMap.put("userName",userName);
        Map result = restFullService.get("https://sso3.jsylvip.com"+"/sso/user/api/checkAdminRole",Map.class,queryMap,null);
        return result==null?"":result.get("datas").toString();
    }

    @GetMapping("/sendSmsCode")
    @ResponseBody
    public Map sendSmsCode(@RequestParam String userName) {
        Map queryMap = Maps.newHashMap();
        queryMap.put("userName",userName);
        Map result = restFullService.get(jmsSsoUrl+"/sso/user/api/sendSmsCode",Map.class,queryMap,null);
        return result;
    }

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap) {
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        //有token直接跳转到首页
        String token = request.getParameter("token");
        if(!StringUtils.isEmpty(token)){
            AjaxResult ajaxResult = ajaxLogin(Constants.TOKEN_LOGIN,token,false,null,null);
            if(ajaxResult == null || ajaxResult.get(AjaxResult.CODE_TAG) != null){
                int code = (int)ajaxResult.get(AjaxResult.CODE_TAG);
                if(code != 0) {
                    return "login";
                }
            }
            // 取身份信息
            SysUser user = ShiroUtils.getSysUser();
            // 根据用户id取出菜单
            List<SysMenu> menus = menuService.selectMenusByRoleKeys(user.getRoles(),user.getActivityIds());
            // 中心下拉选择框
            List<CenterResponse> centerList = user.getCenters();

            mmap.put("menus", menus);
            mmap.put("user", user);
            mmap.put("centerList", centerList);
            mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
            mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
            mmap.put("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
            mmap.put("copyrightYear", Global.getCopyrightYear());
            mmap.put("demoEnabled", Global.isDemoEnabled());
            // mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));

            // 菜单导航显示风格
            String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
            // 移动端，默认使左侧导航菜单，否则取默认配置
            String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

            // 优先Cookie配置导航菜单
            Cookie[] cookies = ServletUtils.getRequest().getCookies();
            for (Cookie cookie : cookies)
            {
                if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
                {
                    indexStyle = cookie.getValue();
                    break;
                }
            }
            String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
            return webIndex;
    }
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe,String luotest_response,String phoneCode) {
        if(!StringUtils.isEmpty(username) && !username.equals(Constants.TOKEN_LOGIN)) {
            if (ACTIVE.equals("druid") && !checkCode(luotest_response)) {
               // return error("请输入验证码！");
            }
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe,phoneCode);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return success();
        } catch (AuthenticationException e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    private boolean checkCode(String luotestResponse){
        Map<String, Object> params = new HashMap<String, Object>();
        CheckCodeResponse response = restFullService.post("https://captcha.luosimao.com/api/site_verify?api_key="+luosimaoapiKey+"&response="+luotestResponse, "/", CheckCodeResponse.class, params, restFullService.getJsonHeader());
        logger.error(String.format("checkCode result: %s", JSON.toJSON(response)));
        if(response!=null && response.getRes()!=null && response.getRes().equals("success")){
            return true;
        }
        return false;
    }


    @GetMapping("/unauth")
    public String unauth() {
        return "error/unauth";
    }
}
